package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.domain.Question;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.EachLoveFanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author ck
 * @date 2021/11/16 19:39
 */

@DubboService
public class FriendApiImpl implements FriendApi{


    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(Long userId, Long friendId) {
        //1、保存自己的好友数据
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("friendId").is(friendId));
        //1.1 判断好友关系是否存在
        if(!mongoTemplate.exists(query, Friend.class)) {
            //1.2 如果不存在，保存
            Friend friend1 = new Friend();
            friend1.setUserId(userId);
            friend1.setFriendId(friendId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }
        //1.2 如果不存在保存
        //2、保存好友的好友数据
        Query query1 = Query.query(Criteria.where("userId").is(friendId)
                .and("friendId").is(userId));
        //2.1 判断好友关系是否存在
        if(!mongoTemplate.exists(query1, Friend.class)) {
            //2.2 如果不存在，保存
            Friend friend1 = new Friend();
            friend1.setUserId(friendId);
            friend1.setFriendId(userId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }

    }

    @Override
    public List<Friend> findByUserId(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        return friends;
    }

    @Override
    public void remove(Long userId, Long likeUserId) {
        //1、保存自己的好友数据
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("friendId").is(likeUserId));
        //1.1 判断好友关系是否存在
        if(mongoTemplate.exists(query, Friend.class)) {
            //1.2 如果存在，删除
            mongoTemplate.remove(query,Friend.class);
        }
        //1.2 如果不存在保存

        //2、删除好友的好友数据
        Query query1 = Query.query(Criteria.where("userId").is(likeUserId)
                .and("friendId").is(userId));
        //2.1 判断好友关系是否存在
        if(mongoTemplate.exists(query1, Friend.class)) {
            //2.2 如果存在，不保存
            mongoTemplate.remove(query1,Friend.class);
        }
    }
}
